package com.benchmark.springboot.interceptor;

import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Auto-Scaling hpa
 *
 * @author yu 2019/3/27.
 */
@Configuration
public class RequestCounterInterceptor implements HandlerInterceptor {

    private static final String METRICS_HTTP_REQUESTS_TOTAL = "http_requests_total";
    private static final String TAG_METHOD = "method";
    private static final String TAG_HANDLER = "handler";
    private static final String TAG_STATUS = "status";

    @Resource
    private MeterRegistry registry;

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {

        String handlerLabel = handler.toString();
        // get short form of handler method name
        if (handler instanceof HandlerMethod) {
            Method method = ((HandlerMethod) handler).getMethod();
            handlerLabel = method.getDeclaringClass().getSimpleName() + "." + method.getName();
        }

        Counter http_requests_total = registry.find(METRICS_HTTP_REQUESTS_TOTAL)
                .tag(TAG_METHOD, request.getMethod())
                .tag(TAG_HANDLER, handlerLabel)
                .tag(TAG_STATUS, Integer.toString(response.getStatus()))
                .counter();

        if (http_requests_total == null) {
            synchronized (this) {
                if (http_requests_total == null) {
                    http_requests_total = registry.counter(METRICS_HTTP_REQUESTS_TOTAL, TAG_METHOD, request.getMethod(),
                            TAG_HANDLER, handlerLabel, TAG_STATUS, Integer.toString(response.getStatus()));
                }
            }
        }
        http_requests_total.increment();
    }
}
